#include "factory.h"

void factory_init(Factory_t* pf, int thread_num, int capacity)
{
    que_init(&pf->que, capacity);
    pthread_cond_init(&pf->cond, NULL);
    pf->pthid = (pthread_t *)calloc(thread_num, sizeof(pthread_t));
    pf->flag = 0;
}

void factory_start(Factory_t *pf, int thread_num)
{
    if (pf->flag != 1)
    {
        for (int i = 0; i < thread_num; i ++)
        {
            pthread_create(pf->pthid + i, NULL, thread_handle, pf);

        }
        pf->flag = 1;
    }
}

void cleanup_handler(void *arg)
{
    pthread_mutex_unlock((pthread_mutex_t *)arg);
}

void* thread_handle(void *p)
{
#ifdef DEBUG
        printf("thread thid = %ld\n", syscall(SYS_gettid));
#endif

    Factory_t *pf = (Factory_t *)p; // 线程池
    pQue_t pq = &pf->que; // 客户队列
    pNode_t pcur = (pNode_t)malloc(sizeof(Node_t)); // 要从客户队列拿的任务

    while (1)
    {
        pthread_mutex_lock(&pq->mutex);
        pthread_cleanup_push(cleanup_handler, &pq->mutex);

        if (pq->que_size == 0) // 队列为空就睡觉
        {
            pthread_cond_wait(&pf->cond, &pq->mutex); // 睡觉的时候锁会解开
        }
        que_get(pq, &pcur); // 把耗时的free(pcur)操作拿到外面去做
        
        pthread_cleanup_pop(0);

        if (pcur != NULL)
        {
            train_file(pcur->new_fd);
            free(pcur);
            pcur = NULL;
        }
    }
}